import React, {useEffect, useState} from "react";
import { modalPropsType } from "@/constants/types";
import { useModel } from "@umijs/max";
import { Modal, Form, Input, Select, DatePicker, InputNumber, Checkbox, Space, Radio, Upload, Button } from "antd";
import { MinusOutlined, PlusOutlined } from "@ant-design/icons";
import { fileUpload } from "@/services/common";
import type { UploadProps } from 'antd/es/upload';
import type { UploadFile } from 'antd/es/upload/interface';
import { useComponentDidMount } from "@/hooks";
import { fetchCouponOptions, fetchActivityDetail } from '../../services';
import dayjs from "dayjs";

const {Item} = Form;
const rules = [{required: true}];
const initValues = {
  rewards: [{}]
};
const labelCol = {
  span: 5
}

const ActivityUpdate = ({onCancel, onSubmit, title, visible, loading, currentRow}: modalPropsType) => {
  const [form] = Form.useForm();
  const { getDict } = useModel('dictModel');
  const activityTypes = getDict('activityType');
  const rewardTimeTypes = getDict('rewardTimeType');
  const couponTypes = getDict('couponType');

  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [couponOptions, setCouponOptions] = useState([]);
  
  const handleSubmit = async () => {
    const res = await form.validateFields();
    onSubmit({
      ...res,
      rewards: res.rewards.map((v: any) => ({
        rewardId: v?.rewardId,
        rewardName: v?.rewardName,
        rewardType: v?.rewardType
      })),
      id: currentRow?.id,
      customerAttachments: res?.customerAttachments?.[0]?.response,
      rewardStartTime: res?.rewardTime?.[0]?.format('YYYY-MM-DD 00:00:00'),
      rewardEndTime: res?.rewardTime?.[1]?.format('YYYY-MM-DD 23:59:59'),
      startTime: res?.time?.[0]?.format('YYYY-MM-DD 00:00:00'),
      endTime: res?.time?.[1]?.format('YYYY-MM-DD 23:59:59'),
      rewardTime: undefined,
      time: undefined,
      isLimit: undefined
    });
  }

  const normFile = (e: any) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e?.fileList;
  };
  const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) => setFileList(newFileList);

  const uploadFileReq = ({file, filename, onSuccess, onError, data = {}}: any) => {
    const formData = new FormData();
    formData.append(filename, file);
    Object.keys(data).forEach(key => {
      formData.append(key, data?.[key]);
    })
    fileUpload(formData).then(
      res => {
        if (res?.code === '0') {
          onSuccess(res?.data);
        } else {
          onError(res?.data)
        }
      }
    )
  }

  useComponentDidMount(() => {
    fetchCouponOptions().then(
      data => {
        setCouponOptions(data || []);
      }
    )
  });

  useEffect(() => {
    if (currentRow?.id) {
      fetchActivityDetail({id: currentRow?.id}).then(
        res => {
          form.setFieldsValue({
            ...res,
            isLimit: res?.rewardNum === -1,
            time: res?.startTime && res?.endTime ? [dayjs(res?.startTime), dayjs(res?.endTime)] : [],
            rewardTime: res?.rewardStartTime && res?.rewardEndTime ? [dayjs(res?.rewardStartTime), dayjs(res?.rewardEndTime)] : [],
          });
        }
      )
    }
  }, [JSON.stringify(currentRow?.id)]);

  return (
    <Modal
      open={visible}
      title={title}
      onCancel={onCancel}
      onOk={handleSubmit}
      confirmLoading={loading}
      maskClosable={false}
      width="700px"
    >
      <Form form={form} className="modal-form-padding" initialValues={initValues} labelCol={labelCol}>
        <Item label="活动名称" name="name" rules={rules}>
          <Input />
        </Item>
        <Item label="活动类型" name="type" rules={rules}>
          <Select options={activityTypes} />
        </Item>
        <Item label="活动时间" name="time" rules={rules}>
          <DatePicker.RangePicker />
        </Item>
        <Item noStyle shouldUpdate={(prev, next) => prev.type !== next.type}>
          {({getFieldValue}) => {
            const type = getFieldValue('type');
            if (type === '3') {
              return (
                <Item label="指定客户" rules={rules} name="customerAttachments" valuePropName="fileList" getValueFromEvent={normFile}>
                  <Upload 
                    maxCount={1} 
                    customRequest={uploadFileReq}
                    onChange={handleChange}
                    fileList={fileList}
                    data={{businessCode: 'activity_customer'}} 
                  >
                    {fileList.length >= 1 ? null : (
                      <Button style={{width: 200}} icon={<PlusOutlined />} type="default">上传</Button>
                    )}
                  </Upload>
                </Item>
              );
            }
          }}
        </Item>
        <Item label="活动奖励" required>
          <Form.List name="rewards">
            {(fields, { add, remove }) => (
              <div style={{ display: 'flex', rowGap: 16, flexDirection: 'column' }}>
                {fields.map((field, fieldIndex) => (
                  <Space.Compact block key={field.name}>
                    <Item noStyle hidden name={[field.name, 'rewardId']}>
                      <Input />
                    </Item>
                    <Item noStyle name={[field.name, 'rewardType']}>
                      <Select style={{width: 200}} options={couponTypes} onChange={() => {
                        form.setFieldValue(['rewards', field.name, 'rewardName'], null);
                        form.setFieldValue(['rewards', field.name, 'rewardId'], null);
                      }} />
                    </Item>
                    <Item noStyle shouldUpdate>
                      {({getFieldValue}) => {
                        const rewardType = getFieldValue(['rewards', field.name, 'rewardType']);
                        const arr = couponOptions.filter((v: any) => v.type === rewardType) || [];
                        return (
                          <Item noStyle name={[field.name, 'rewardName']}>
                            <Select 
                            style={{width: 200}} 
                            options={arr.map((v: any) => ({label: v.name, value: v.name}))}
                            onChange={val => {
                              const id = couponOptions.find((v: any) => v.name === val)?.id;
                              form.setFieldValue(['rewards', field.name, 'rewardId'], id);
                            }} />
                          </Item>
                        );
                      }}
                    </Item>
                    <Button icon={<PlusOutlined />} onClick={add}></Button>
                    {fieldIndex > 0 && <Button icon={<MinusOutlined />} onClick={() => remove(field.name)}></Button>}
                  </Space.Compact>
                ))}
              </div>
            )}
          </Form.List>
        </Item>
        <Item noStyle shouldUpdate={(prev, next) => prev.type !== next.type}>
          {({getFieldValue}) => {
            const type = getFieldValue('type');

            if (type === '2') {
              return (
                <Item label="奖励总数量" required>
                  <Space>
                    <Item noStyle shouldUpdate>
                      {({getFieldValue}) => {
                        const isLimit = getFieldValue('isLimit');
                        return (
                          <Item noStyle name="rewardNum">
                            <InputNumber disabled={isLimit} min={isLimit ? -10 : 0} />
                          </Item>
                        );
                      }}
                    </Item>
                    <Item noStyle name="isLimit" valuePropName="checked">
                      <Checkbox onChange={(e) => {
                        const val = e.target.checked;
                        if (val) {
                          form.setFieldValue('rewardNum', -1);
                        }
                      }}>不限制</Checkbox>
                    </Item>
                  </Space>
                </Item>
              )
            }
          }}
        </Item>
        <Item label="优惠券有效期" required>
          <Space>
            <Item noStyle name="rewardTimeType">
              <Radio.Group options={rewardTimeTypes} />
            </Item>
            <Item noStyle shouldUpdate={(prev, next) => prev.rewardTimeType !== next.rewardTimeType}>
              {({getFieldValue}) => {
                const rewardTimeType = getFieldValue('rewardTimeType');
                if (rewardTimeType === '1') {
                  return (
                    <Item noStyle name="rewardTime">
                      <DatePicker.RangePicker />
                    </Item>
                  );
                }
                if (rewardTimeType === '2') {
                  return (
                    <Space>
                      <Item noStyle name="rewardExpiredDay" extra='天'>
                        <InputNumber />
                      </Item>
                      <span>天</span>
                    </Space>
                  );
                }
              }}
            </Item>
          </Space>
        </Item>
        <Item noStyle>
          {({getFieldValue}) => {
            const type = getFieldValue('type');
            if (type === '2') {
              return (
                <Item label='活动地址' name="url">
                  <Input />
                </Item>
              );
            }
          }}
        </Item>
      </Form>
    </Modal>
  );
}
export default ActivityUpdate;